global class NCProductRemindUtil {
    

     @future(callout=true)
     global static void remindToUser(){

      try {
            Set<String> invocodes = new Set<String>();//存货编码
            Set<String> vbatchcodes = new Set<String>();//批次号
            Map<String,Id > prMap = new Map<String,Id>();//Id ; 
            Map<String , ProductRemind__c > contentMap = new Map<String,ProductRemind__c>();//提示内容
            for( ProductRemind__c pr: [select Id ,Product__r.NCCode__c,Product__r.ProductName__c ,BatchCode__c ,RemindContent__c  
              from ProductRemind__c 
              where EndDate__c >:Date.today()]){
                
                invocodes.add(pr.Product__r.NCCode__c);
                vbatchcodes.add(pr.BatchCode__c);
                prMap.put(pr.Product__r.NCCode__c +'-'+pr.BatchCode__c,pr.Id );
                contentMap.put(pr.Id , pr );

            }
            if(invocodes.size() == 0 || vbatchcodes.size() == 0) return;

            Date d = System.today().addDays(-2);

            String startDate   = Datetime.newInstance(d.year(), d.month(), d.day() ).format('yyyy-MM-dd');

            String sql = 'select distinct invcode, vbatchcode,custcode from v_saleckInfo_esb  where daccountdate >=\''+startDate+'\'  ' +

            ' and invcode in (\''+String.join(new List<String>(invocodes), '\',\'')+'\') ' +
            ' and vbatchcode in  (\''+String.join(new List<String>(vbatchcodes), '\',\'')+'\') ' ; 

           // if( acccodes.size() > 0 ) sql += ' and custcode||invcode||vbatchcode not in (\''+String.join(new List<String>(acccodes), '\',\'')+'\') ' ; 
             String url = Label.queryResposityURL;
            // sql =  'select a.*,rownum from ('+ sql+  ') a  where rownum <= 100   ';
             System.debug('NCProductRemindUtil==>'+sql);

              sql = '{"data":"'+sql+'"}';
              //请求
              vbatchcodes.clear();
              invocodes.clear();

              HttpRequest req = new HttpRequest();
              req.setBody(sql);
              req.setMethod('POST');
              req.setHeader('Content-Type','text/plain');
              req.setEndpoint(url);
              HttpResponse res = Utils.postRequest(req, 2);
              System.debug(res.getBody());
                Map<String,Object> r = null;
                    //如果是测试
              if(Test.isRunningTest()){
                Map<String,Object>  resBody= new Map<String,Object>();
                resBody.put('code','0');
                resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"custcode\":\"111\",\"invcode\":\"xx001\",\"vbatchcode\":\"001234\"}]}');
                  r =  resBody;
              }else{
                r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
              }
              if(r.get('code') == 0 || r.get('code') == '0'){
                 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                  if( rs.get('result') == 1 ){

                      List<Object> datas = (List<Object>)rs.get('data');

                      List<ProductRemindDetails__c> prdList = new List<ProductRemindDetails__c>();
                      
                    Set<String> onlyKeys = new Set<String>();
                    Set<String> acccodes = new Set<String>(); //客户编码
                      for(Object o : datas){
                         Map<String,Object> mo = (Map<String,Object>) o;

                         onlyKeys.add(DataUtil.getStringValue(mo.get('custcode'))+DataUtil.getStringValue(mo.get('invcode'))+DataUtil.getStringValue(mo.get('vbatchcode')));
                         acccodes.add(DataUtil.getStringValue(mo.get('custcode')));
                      }

                      for(ProductRemindDetails__c prd : [select AccountNumber__c ,ProductRemind__r.Product__r.NCCode__c ,ProductRemind__r.BatchCode__c  from ProductRemindDetails__c where AsmKey__c in:onlyKeys and ProductRemind__c in: prMap.values()   ]){
                        onlyKeys.remove(prd.AccountNumber__c+prd.ProductRemind__r.Product__r.NCCode__c+prd.ProductRemind__r.BatchCode__c);
                      }
                      Map<String,Account>accUserMap = new Map<String,Account>();
                      Map<String,Id> userMap = new Map<String,Id>();
                      for(Account acc : [select Id,Name  ,AccountNumber,OwnerId,Owner.IsActive ,Owner.ManagerId   from Account where AccountNumber in: acccodes and Owner.Profile.Name != '系统管理员' ]){
                        
                         accUserMap.put(acc.AccountNumber ,acc);
                         userMap.put(acc.AccountNumber, acc.Owner.IsActive ?acc.OwnerId : acc.Owner.ManagerId  );

                      }
                      acccodes.clear();
                      Set<String> aNList = new Set<String>();
                      for(Object o : datas){

                         Map<String,Object> mo = (Map<String,Object>) o;
                         if(!onlyKeys.contains(DataUtil.getStringValue(mo.get('custcode'))+DataUtil.getStringValue(mo.get('invcode'))+DataUtil.getStringValue(mo.get('vbatchcode')))) continue;
                         String invcode = DataUtil.getStringValue(mo.get('invcode'));
                         String vbatchcode = DataUtil.getStringValue(mo.get('vbatchcode'));

                         ProductRemindDetails__c prd = new ProductRemindDetails__c();
                         prd.ProductRemind__c = prMap.get(invcode+'-'+vbatchcode);
                         prd.AccountNumber__c = DataUtil.getStringValue(mo.get('custcode'));
                         if(userMap.containsKey(prd.AccountNumber__c))prd.NotePerson__c = userMap.get(prd.AccountNumber__c);
                        if(accUserMap.containsKey(prd.AccountNumber__c ) )prd.Account__c  = accUserMap.get(prd.AccountNumber__c ).Id ;
                         if(prd.Account__c == null ){
                            aNList.add(prd.AccountNumber__c);
                            continue;
                         }
                         prd.NotePerson__c = userMap.get(prd.AccountNumber__c);
                         prdList.add(prd);

                      }
                      onlyKeys.clear();
                    // accUserMap.clear();
                      prMap.clear();

                      SavePoint sp = Database.setSavepoint();
                      try {

                          if(prdList.size() >0 )insert prdList; 

                          List<Task> tList =new List<Task>();
                          //提示内容
                          for(ProductRemindDetails__c prd : prdList){

                             
                              Task t = new Task();

                              t.OwnerId = userMap.get(prd.AccountNumber__c);
                              t.Description =accUserMap.get(prd.AccountNumber__c ).Name +'('+prd.AccountNumber__c+') 首次订货重要提醒:' +  contentMap.get(prd.ProductRemind__c).Product__r.ProductName__c +contentMap.get(prd.ProductRemind__c).BatchCode__c +contentMap.get(prd.ProductRemind__c).RemindContent__c; 
                              t.Subject = '客户首次订货重要提醒!';
                              t.Status= 'Open';
                              t.ActivityDate = System.today() ; 
                              t.WhatId =  prd.ProductRemind__c;
                              if(t.OwnerId == null) {
                                 aNList.add(prd.AccountNumber__c);
                                 continue;
                              }
                              tList.add(t);

                          }

                          if(tList.size() > 0 ) insert tList ;
                          if(aNList.size() > 0 )sendMail(new List<String>{Label.ProductRemindMail},'产品批次提醒报错','产品批次提醒报错','未匹配到客户或客户未分配!'+String.join(new List<String>(aNList), ','));




                      }catch (Exception e) {
                          Database.rollback(sp);
                          sendMail(new List<String>{Label.ProductRemindMail},'产品批次提醒报错','产品批次提醒报错',e.getMessage());
                      }

                  }else{
                      sendMail(new List<String>{Label.ProductRemindMail},'产品批次提醒报错','产品批次提醒报错',String.valueOf(rs.get('result_msg')) );
                  }
              }else{
                  sendMail(new List<String>{Label.ProductRemindMail},'产品批次提醒报错','产品批次提醒报错',res.getBody() );
              }
          
      }catch (Exception e) {
          sendMail(new List<String>{Label.ProductRemindMail},'产品批次提醒报错','产品批次提醒报错',e.getMessage()+e.getStackTraceString() );
      }
      
     
    }
    global static void sendMail( List<String> toAddresses,String title , String subject ,String msg  ){
        Messaging.SingleEmailMessage[] mList = new Messaging.SingleEmailMessage[]{};

        Messaging.reserveSingleEmailCapacity(1);
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(toAddresses);
        //mail.setReplyTo('support@acme.com');
        mail.setSenderDisplayName(title);
        mail.setSubject(subject );
        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setPlainTextBody(msg);
        mList.add(mail);
        Messaging.sendEmail(mList);
       
    }

}